//
//  WBMainViewController.swift
//  Weibo
//
//  Created by yinbo on 2018/2/27.
//  Copyright © 2018年 yinbo. All rights reserved.
//
 import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    //定时器
    var timer:Timer?
    
    
    deinit {
        //销毁计时器
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
        setupNewFeatureViews()
        setupTimer()
        delegate = self
        NotificationCenter.default.addObserver(self, selector:#selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        //测试未读数量
//        WBNetworkManager.shared.unreadCount { (count) in
//            print("\(count)新微博")
//        }
        // Do any additional setup after loading the view.
    }
    //使用代码控制设备方向，好处：可以在需要横屏的时候，单独处理
       //设置支持方向之后，当前的控制器以及子控制器都会遵循这个方向
       //如果播放视频的话，通常是通过Modal展示的
 
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    @objc private func userLogin(n:Notification){
        print("用户登录通知\(n)")
        var when = DispatchTime.now()
        if n.object != nil{
            SVProgressHUD.setDefaultMaskType( .gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            //修改延迟时间
            when = DispatchTime.now()+2
        }
        DispatchQueue.main.asyncAfter(deadline:when) {
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
           self.present(nav, animated: true, completion: nil)
        }
        
    }
    //MARK:-监听方法
    @objc  func composeStatus(){
        print("撰写方法")
//        let vc = UIViewController()
//        vc.view.backgroundColor=UIColor.cz_random()
//        let nv = UINavigationController(rootViewController: vc)
//        present(nv, animated: true, completion: nil)
        let  v:WBComposeTypeView = WBComposeTypeView.compostTypeView() 
//        v.frame = view.bounds
        //注意闭包的循环引用
        v.show { [weak v](clsName) in
            print(clsName)
            guard let clsName = clsName,let cls = NSClassFromString(Bundle.main.namespace+"."+clsName) as? UIViewController.Type else{
                v?.removeFromSuperview()
                return
            }
          
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav,animated: true, completion: {
                v?.removeFromSuperview()
            })
           
            
        }
        
    }
     lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
//MARK:新特性视图处理
extension WBMainViewController{
    
    func setupNewFeatureViews(){
        if !WBNetworkManager.shared.userLogon{
            return
        }
        //1.检查版本是否更新
        let v = isNewVersion ? WBNewFeatureView.newfeatureView() : WBWelcomView.welcomeView()
        //2.如果更新，显示新特性，否则显示欢迎
//        v.frame = view.bounds
        //3.添加视图
        view.addSubview(v)
        
    }
    //extension可以有计算型属性，不会占用存储空间
    var isNewVersion:Bool{
//        print(Bundle.main.infoDictionary)
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print(currentVersion)
        let path:String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile:path)) ?? ""
        print(path)
        print(sandboxVersion)
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        return currentVersion != sandboxVersion
//        return currentVersion == sandboxVersion

    }
}


//MARK: -时钟相关方法
extension WBMainViewController{
    func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    @objc private func updateTimer(){
        print(#function)
        if !WBNetworkManager.shared.userLogon{
            return
        }
        WBNetworkManager.shared.unreadCount { (count) in
            //设置首页tabbarItem的badgeNumber
            self.tabBar.items?[0].badgeValue = count>0 ? "\(count)" : nil
            //设置app的badgeNumber,从iOS8.0之后，需要用户授权
            UIApplication.shared.applicationIconBadgeNumber = count
            
        }
    }
    
}
//MARK: -UITabBarControllerDelegate
extension WBMainViewController:UITabBarControllerDelegate{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let idx:Int = childViewControllers.index(of: viewController)!
        if selectedIndex == 0 && idx == selectedIndex{
            print("重复点击首页")
            //让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+3, execute: {
                    vc.loadData()
            })
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        return true
    }
}

//MARK: -设置界面
extension WBMainViewController{
    //设置撰写按钮
    func  setupComposeButton() {
        tabBar.addSubview(composeButton)
        //按钮高度
        let count = CGFloat(childViewControllers.count)
        //将向内缩进的宽度减少，能够让按钮的宽度变大，盖住容错点，防止穿帮！
        let w = tabBar.bounds.width/count-1
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    //设置所有子控制器
    func setupChildControllers(){
        //let array:[[String:Any]]=[["clsName":"WBHomeViewController","title":"首页","imageName":"home","visitorInfo":["imageName":"","message":"关注一些人，回到这里看看有什么惊喜"]],["clsName":"WBMessageViewController","title":"消息","imageName":"message_center","visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微薄，发给你的消息，都会在这里收到通知"]],["clsName":"UIViewController"],["clsName":"WBDiscoverViewController","title":"发现","imageName":"discover","visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，最新、最热微博尽在掌握，不会与实事潮流擦肩而过"]],["clsName":"WBProfileViewController","title":"我","imageName":"profile","visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]]
        //let data=try! JSONSerialization.data(withJSONObject: array, options: [])
        //let fileURL = NSURL.fileURL(withPath: "/Users/mac/Desktop/demo.json")
        //(data as NSData).write(toFile: "/Users/yinbo/Desktop/demo.json", atomically: true)
        let docDic = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDic as NSString).appending("/main.json")
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil{
            let path = Bundle.main.path(forResource: "main", ofType: "json")
            data = NSData(contentsOfFile: path!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String:Any]]  else{
            return
        }
        var arrayM = [UIViewController]()
        for dict in array!{
            arrayM.append(controller(dic: dict))
        }
        viewControllers = arrayM
        
    }
    //使用字典创建一个子控制器
    
    func controller(dic:[String:Any])->UIViewController{
        guard let clsName = dic["clsName"] as? String,let title = dic["title"]as? String,let imgName = dic["imageName"]as? String,let cls = NSClassFromString(Bundle.main.namespace+"."+clsName) as? WBBaseViewController.Type ,let visitorDic = dic["visitorInfo"] as? [String:String] else{
            return UIViewController()
        }
        let vc = cls.init()
        
        vc.title = title
        
        vc.visitorInfoDic = visitorDic
        vc.tabBarItem.image = UIImage(named:"tabbar_"+imgName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imgName+"selected")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        //设置tabbar的标题字体（大小）,系统默认是12号字
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
        //实例话导航控制器会调用push方法将rootvc压栈
        let nav = WBNavigationController(rootViewController: vc)
        return nav
        
     }
}
